package com.codechuan.demo.ui.mySchedule;


import static com.google.android.material.internal.ContextUtils.getActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codechuan.demo.MainActivity;
import com.codechuan.demo.R;
import com.codechuan.demo.adapter.ScheduleBaseAdapter;
import com.codechuan.demo.common.Constant;
import com.codechuan.demo.dto.CityInfo;
import com.codechuan.demo.dto.Schedule;
import com.codechuan.demo.dto.SysSchedule;
import com.codechuan.demo.dto.TokenObject;
import com.codechuan.demo.ui.home.HomeFragment;
import com.codechuan.demo.ui.login.LoginActivity;
import com.codechuan.demo.ui.myScheduleAdd.myScheduleAdd;
import com.codechuan.demo.utils.DialogUtil;
import com.codechuan.demo.utils.HttpControllerUtil;
import com.codechuan.demo.utils.MyHttpUtil;
import com.example.libbaiduselectlocation.BDLocationActivity;
import com.example.libbaiduselectlocation.SelectLocationBDActivity;
import com.example.libbaiduselectlocation.bean.SelectLocationBDBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class MySchedule extends BDLocationActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
    View inflate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_my_schedule);
        // 设置按钮事件
        Button schedule_jump_home = findViewById(R.id.schedule_jump_home);
        schedule_jump_home.setOnClickListener(this);

        Button schedule_jump_add = findViewById(R.id.schedule_jump_add);
        schedule_jump_add.setOnClickListener(this);

        // 判断城市是否定位
        if (Constant.cityInfo == null) {
            try {
                Intent intent = new Intent();
                intent.setClass(Constant.context, LoginActivity.class);
                startActivity(intent);
                DialogUtil.showDialog(Constant.context, "请先定位城市.");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        // 查询行程数据
        Constant.executorService.execute(() -> {
            String jsonObjectString = HttpControllerUtil.getWeChatMiniMyOrderOrMyScheduleOrder();
            Constant.handler.post(() -> {
                DialogUtil.showDialog(Constant.context, "获取中,请稍后");
            });
            if (jsonObjectString == null) {
                DialogUtil.showDialog(Constant.context, "暂无行程.");
            }
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.parseObject(jsonObjectString);
            } catch (Exception e) {
                Constant.handler.post(() -> DialogUtil.showDialog(Constant.context, "哈喽官方提示:" + jsonObjectString));
                if (jsonObjectString.contains("登录信息已失效, 请重新登录")) {
                    Constant.executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            // 修改主号信息
                            TokenObject tokenObject = new TokenObject(Constant.MAIN_TOKEN, Constant.MAIN_TICKET
                                    , "", "1", 0, "1", Constant.USER_ACCOUNT);
                            MyHttpUtil.updateUserTokenStatus(tokenObject);
                            Constant.MAIN_ACCOUNT_STATUS = "登录信息已失效, 请重新登录";
                        }
                    });
                }
                return;
            }
            JSONArray data = null;
            if (jsonObject.getString("code").equals("0")) {
                data = jsonObject.getJSONArray("data");
            }
            ArrayList<SysSchedule> scheduleArrayList = new ArrayList<>();
            assert data != null;
            for (Object scheduleDataList : data) {
                JSONObject schedule = JSONObject.parseObject(scheduleDataList.toString());
                JSONObject startPosition = schedule.getJSONObject("startPosition");
                JSONObject endPosition = schedule.getJSONObject("endPosition");

                SysSchedule sysSchedule = new SysSchedule();
                sysSchedule.setDriverJourneyGuid(schedule.getString("driverJourneyGuid"));
                sysSchedule.setStartCityName(startPosition.getString("cityName") + startPosition.getString("adName"));
                sysSchedule.setEndCityName(endPosition.getString("cityName") + endPosition.getString("adName"));
                sysSchedule.setSonOrderNumber(schedule.getJSONArray("paxOrderList").size());
                scheduleArrayList.add(sysSchedule);
            }
            Constant.handler.post(() -> {
                // 创建自定义适配器对象
                ListView listView = findViewById(R.id.scheduleListData);
                ScheduleBaseAdapter scheduleBaseAdapter = new ScheduleBaseAdapter(Constant.context, scheduleArrayList);
                listView.setAdapter(scheduleBaseAdapter);
            });
        });
    }

    private TextView xc_start_address;
    private TextView xc_end_address;

    @Override
    public void onClick(View view) {
        // 返回首页按钮
        if (R.id.schedule_jump_home == view.getId()) {
            Intent intent = new Intent();
            intent.setClass(this, LoginActivity.class);
            startActivity(intent);
        }
        // 添加行程按钮
        if (R.id.schedule_jump_add == view.getId()) {
            // 创建自定义布局以设置宽度
            inflate = LayoutInflater.from(this).inflate(R.layout.activity_my_schedule_add, null);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
            TextView xc_start_time = inflate.findViewById(R.id.xc_start_time);
            xc_start_time.setText(format.format(new Date()));
            // 提交发布行程
            Button submit_xc = inflate.findViewById(R.id.submit_xc);
            xc_start_address = inflate.findViewById(R.id.xc_start_address);
            xc_end_address = inflate.findViewById(R.id.xc_end_address);

            submit_xc.setOnClickListener(view1 -> {
                String xc_start_address_string = xc_start_address.getText().toString();
                if (xc_start_address_string.equals("请输入起点位置") || xc_start_address_string.isEmpty()) {
                    DialogUtil.showDialog(Constant.context, "起点位置不正确");
                    return;
                }
                String xc_end_address_string = xc_end_address.getText().toString();
                if (xc_end_address_string.equals("请输入终点位置") || xc_end_address_string.isEmpty()) {
                    DialogUtil.showDialog(Constant.context, "终点位置不正确");
                    return;
                }
                String xc_start_time_string = xc_start_time.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        CityInfo startCityInfo = HttpControllerUtil.getCityInfo(xc_start_address_string);
                        CityInfo endCityInfo = HttpControllerUtil.getCityInfo(xc_end_address_string);
                        if (startCityInfo == null) {
                            Constant.handler.post(() -> DialogUtil.showDialog(Constant.context, "起点定位失败"));
                            return;
                        }
                        if (endCityInfo == null) {
                            Constant.handler.post(() -> DialogUtil.showDialog(Constant.context, "终点定位失败"));
                            return;
                        }
                        Schedule schedule = new Schedule();
                        schedule.setStartCityCode(startCityInfo.getCityId());
                        schedule.setStartAdCode(startCityInfo.getAdCode());
                        schedule.setStartShortAddr(startCityInfo.getDistrict());
                        schedule.setStartLon(Double.parseDouble(startCityInfo.getLng()));
                        schedule.setStartLat(Double.parseDouble(startCityInfo.getLat()));
                        schedule.setStartLongAddr(xc_start_address_string);
                        schedule.setStartCityName(startCityInfo.getCity());

                        schedule.setEndCityCode(endCityInfo.getCityId());
                        schedule.setEndAdCode(endCityInfo.getAdCode());
                        schedule.setEndShortAddr(endCityInfo.getDistrict());
                        schedule.setEndLon(Double.parseDouble(endCityInfo.getLng()));
                        schedule.setEndLat(Double.parseDouble(endCityInfo.getLat()));
                        schedule.setEndLongAddr(xc_start_address_string);
                        schedule.setEndCityName(endCityInfo.getCity());
                        schedule.setTime(xc_start_time_string);

                        // 执行发布行程
                        String code = HttpControllerUtil.submit_WeChatMini(schedule);
                        if (code!= null) {
                            Constant.handler.post(() -> DialogUtil.showDialog(Constant.context, "发布成功"));
                            Intent intent = new Intent();
                            intent.setClass(Constant.context, MySchedule.class);
                            startActivity(intent);
                        } else {
                            Constant.handler.post(() -> DialogUtil.showDialog(Constant.context, "发布失败"));
                        }
                    }
                }).start();
            });
            // 时间按钮
            Button select_time = inflate.findViewById(R.id.sc_select_time);
            // 日期弹出框和设置宽度
            select_time.setOnClickListener(view2 -> {
                DatePickerDialog datePickerDialog = new DatePickerDialog(this, this, 2024, 7, 19);
                datePickerDialog.show();
            });

            // 渲染弹窗
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            AlertDialog alertDialog = builder.create();
            alertDialog.setView(inflate);
            alertDialog.show();
            Window window = alertDialog.getWindow();
            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(alertDialog.getWindow().getAttributes());
            lp.width = Constant.dm.widthPixels * 4 / 5 + 150;
            window.setAttributes(lp);

            // 取消发布行程
            Button submit_qx = inflate.findViewById(R.id.submit_qx);
            submit_qx.setOnClickListener(view12 -> alertDialog.dismiss());

            // 起点位置按钮
            Button selectStartAddress = inflate.findViewById(R.id.selectStartAddress);
            selectStartAddress.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SelectLocationBDActivity.Companion.startActivityForResult(MySchedule.this, 87);
                }
            });

            // 终点位置按钮
            Button selectEndAddress = inflate.findViewById(R.id.selectEndAddress);
            selectEndAddress.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SelectLocationBDActivity.Companion.startActivityForResult(MySchedule.this, 88);
                }
            });

        }


    }

    @Override
    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm", Locale.getDefault());
        String time = format.format(new Date());
        TextView xc_start_time = inflate.findViewById(R.id.xc_start_time);
        String moon = "";
        String day = "";
        i1 = i1 + 1;
        if (String.valueOf(i1).length() == 1) {
            moon = "0" + i1;
        } else {
            moon = moon + i1;
        }

        if (String.valueOf(i2).length() == 1) {
            day = "0" + i2;
        } else {
            day = day + i2;
        }

        xc_start_time.setText(i + "-" + moon + "-" + day + " " + time);


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 88 && resultCode == Activity.RESULT_OK) {
            SelectLocationBDBean bean = (SelectLocationBDBean) data.getSerializableExtra("data");
            String district = bean.getLocation().getDistrict();
            String address = bean.getLocation().getAddress();
            Constant.handler.post(() -> {
                xc_end_address.setText(district + address);
            });
        }
        if (requestCode == 87 && resultCode == Activity.RESULT_OK) {
            SelectLocationBDBean bean = (SelectLocationBDBean) data.getSerializableExtra("data");
            String district = bean.getLocation().getDistrict();
            String address = bean.getLocation().getAddress();
            Constant.handler.post(() -> {
                xc_start_address.setText(district + address);
            });
        }
    }

    @Override
    public void onLocation(String s, String s1, String s2, String s3, String s4) {

    }

    @Override
    public void onLocationFail(String s) {

    }
}